import Foundation
import UserNotifications

extension Notification.Name {
    static let notificationTapped = Notification.Name("notificationTapped")
}

class NotificationManager {
    static let shared = NotificationManager()
    private var lastNotificationId: String?
    
    private init() {}
    
    func requestPermission(completion: @escaping (Bool, Error?) -> Void) {
        UNUserNotificationCenter.current().delegate = NotificationDelegate.shared
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
            completion(granted, error)
        }
    }
    
    func sendNotification(for posture: PostureType, overtimeMinutes: Int = 0) {
        // 如果有之前的通知，先移除
        if let lastId = lastNotificationId {
            UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [lastId])
        }
        
        let content = UNMutableNotificationContent()
        content.title = "该切换姿势了"
        
        if overtimeMinutes > 0 {
            content.body = "建议切换到\(posture.nextPosture.title)模式（已超时\(overtimeMinutes)分钟）"
        } else {
            content.body = "建议切换到\(posture.nextPosture.title)模式"
        }
        
        content.sound = .default
        content.interruptionLevel = .timeSensitive
        
        let identifier = UUID().uuidString
        lastNotificationId = identifier
        
        let request = UNNotificationRequest(
            identifier: identifier,
            content: content,
            trigger: nil
        )
        
        UNUserNotificationCenter.current().add(request)
    }
    
    func removeLastNotification() {
        if let lastId = lastNotificationId {
            UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [lastId])
            lastNotificationId = nil
        }
    }
}

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
    static let shared = NotificationDelegate()
    
    private override init() {}
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        NotificationCenter.default.post(name: .notificationTapped, object: nil)
        completionHandler()
    }
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.banner, .sound])
    }
}
